#pragma once

#include <vector>
#include <string>

#include "IFinsCommand.h"
#include "tcpTransport.h"

using namespace std;

#pragma pack(1)
namespace OmronPlc
{
typedef struct __tcp_fins_header{
	unsigned char magic[4];	//固定值 "FINS" 
	unsigned char len[4];	//长度
	unsigned char cmd[4];	//命令
	unsigned char errorCode[4];//固定值为0
	//unsigned char clientCode[4];//PC端IP地址的最后一位
}tcpFinsHeader_S;

typedef struct __tcp_fins_cmd_
{
	/* data */
	tcpFinsHeader_S header;
	unsigned char feild[F_PARAM];	//12个字节为报文内容识别
	unsigned char parameter[];
}tcpFinsCmd_S;

typedef struct __tcp_fins_read_
{
	unsigned char area;
	unsigned char addr[2];	//下标为 0: 地址高位 1： 地址低位
	unsigned char bitPos;	//bit位
	unsigned char length[2];
}tcpFinsReadCmd_S;

typedef struct __tcp_find_write_
{
	unsigned char area;
	unsigned char addr[2];//下标为 0: 地址高位 1： 地址低位 
	unsigned char bitPos;	//bit位
	unsigned char length[2];
	unsigned char value[];
}tcpFinsWriteCmd_S;

typedef struct __tcp_fins_read_response{	//读取数据的返回值
	unsigned char errorCode[2];
	unsigned char value[];
}tcpFinsReadRespons_S;

}
#pragma pack(0)




namespace OmronPlc
{
	class tcpFinsCommand : public IFinsCommand
	{
	private:
		int finsCommandLen = 0;
		uint8_t respFS[1024];
		vector<uint8_t> respFinsData;
		vector<uint8_t> respFins;
		tcpTransport * transport;
		string lastError;
		unsigned char cmdSend[1024];

	public:
		tcpFinsCommand(uint8_t ServiceID = 0x01);
		~tcpFinsCommand();
		string getLastError(){
			return lastError;
		}
		virtual bool Connect();
		virtual void Close();
		virtual void SetRemote(string ipaddr, uint16_t port);
		virtual bool MemoryAreaRead(MemoryArea area, uint16_t address, uint8_t bit_position, uint16_t count);
		virtual bool MemoryAreaWrite(MemoryArea area, uint16_t address, uint8_t bit_position, uint16_t count, uint8_t data[]);

	private:
		bool NodeAddressDataSend();
		bool FrameSend();
	};
}
